package com.myspringsecurity.service;

import com.myspringsecurity.dao.PermissionDao;
import com.myspringsecurity.dao.UserDao;
import com.myspringsecurity.entity.Permission;
import com.myspringsecurity.entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * @author ：Q大侠
 * @date ：Created in 2022/11/1 18:41
 * @description：
 * @modified By：
 * @version:
 */
@Service //该类对象的生命周期交于spring容器管理
public class MyUserService implements UserDetailsService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private PermissionDao permissionDao;

    //注入 dao对象---根据账户查询用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users users = userDao.selectByUsername(username);
        if (users!=null){
            //该用户具有的权限
            Collection<GrantedAuthority> authorities=new ArrayList<>();
            //根据id查询用户权限
            List<Permission> permissions=permissionDao.findByUserid(users.getUserid());
            for (Permission permission : permissions) {
                SimpleGrantedAuthority simpleGrantedAuthority=new SimpleGrantedAuthority(permission.getPercode());
                authorities.add(simpleGrantedAuthority);
            }
            User user = new User(username,users.getUserpwd(),authorities);
            return user;
        }
        return null;
    }


}

